package cn.mengfly.testnrz.netty;

import cn.mengfly.testnrz.nio.NioDemoConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author Mengfly
 */
public class NettyDiscardServer {
    private final int serverPort;
    ServerBootstrap b = new ServerBootstrap();

    public NettyDiscardServer(int port) {
        this.serverPort = port;
    }

    public void runServer() {
        EventLoopGroup bossLoopGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerLoopGroup = new NioEventLoopGroup();
        try {
            // 反应器线程组
            b.group(bossLoopGroup, workerLoopGroup);
            b.channel(NioServerSocketChannel.class);
            b.localAddress(serverPort);
            // 通道参数
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) {
                    socketChannel.pipeline().addLast(new NettyDiscardHandler());
                }
            });
            // 绑定服务器
            ChannelFuture sync = b.bind().sync();
            System.out.println("服务器启动成功, 监听端口：" + sync.channel().localAddress());
            ChannelFuture closeFuture = sync.channel().closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerLoopGroup.shutdownGracefully();
            bossLoopGroup.shutdownGracefully();
        }
    }

    private static class NettyDiscardHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ByteBuf in = (ByteBuf) msg;
            try {
                System.out.println("收到消息，丢弃如下");
                while (in.isReadable()) {
                    byte[] bytes = new byte[in.readableBytes()];
                    in.readBytes(bytes);
                    System.out.print(new String(bytes));
                }
                System.out.println();
            } finally {
                ((ByteBuf) msg).release();
            }
        }
    }

    public static void main(String[] args) {
        int port = NioDemoConfig.SOCKET_PORT;
        new NettyDiscardServer(port).runServer();
    }

}
